package ua.kiev.tosik.price.modules.clients.database.prices;

import org.apache.commons.lang.time.DurationFormatUtils;
import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IPricesDao;
import ua.kiev.tosik.price.database.dao.IPricesFilesDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.PricesFiles;

import javax.swing.*;

public class PricesDeleteWorker extends SwingWorker<PricesFiles, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database.prices");
	private PricesFiles pricesFiles;
	private IPricesDao pricesDao;
	private IPricesFilesDao pricesFilesDao;
	private int rowIndex = -1;

	public PricesDeleteWorker() {
		super();
		logger.debug("Initialize PricesDeleteWorker");
		try {
			pricesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesDao();
			pricesFilesDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createPricesFilesDao();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public void setPricesFiles(PricesFiles pricesFiles) {
		this.pricesFiles = pricesFiles;
	}

	public void setRowIndex(int rowIndex) {
		this.rowIndex = rowIndex;
	}

	@Override
	protected PricesFiles doInBackground() throws Exception {
		firePropertyChange("PRICE_CLEAR_START", false, true);
		long startTime = System.currentTimeMillis();
		if ( pricesDao == null ) {
			logger.error("Dao [PricesDao] is not initialized!");
			throw new Exception("Dao [PricesDao] is not initialized!");
		}
		if ( pricesFilesDao == null ) {
			logger.error("Dao [PricesFilesDao] is not initialized!");
			throw new Exception("Dao [PricesFilesDao] is not initialized!");
		}
		if ( pricesFiles == null ) {
			logger.error("PricesFiles is not defined!");
			throw new Exception("PricesFiles is not defined!");
		}
		pricesDao.deleteByPricesFilesId(pricesFiles.getId());
		pricesFiles.setParsed(false);
		this.pricesFiles = pricesFilesDao.update(pricesFiles);
		logger.debug("Clearing prices done with: " + DurationFormatUtils.formatDuration((System.currentTimeMillis()-startTime), "s.S") + " sec");
		return this.pricesFiles;
	}

	@Override
	protected void done() {
		super.done();
		firePropertyChange("PRICE_CLEAR_DONE", false, true);
		try {
			this.pricesFiles = get();
			firePropertyChange("PRICE_CLEAR_OK", this.rowIndex, this.pricesFiles);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			firePropertyChange("PRICE_CLEAR_ERROR", null, e);
		}
	}

}
